<?php
include_once 'user_include.php';

$start_date = get_date_from_str($_POST['start_date']);
$end_date = get_date_from_str($_POST['end_date']);

$start_date_str = get_string_from_date($_POST['start_date']);
$end_date_str = get_string_from_date($_POST['end_date']);

$parsed_start_date = parse_dates($_POST['start_date']);
$parsed_end_date = parse_dates($_POST['end_date']);
$id = $_POST['id'];
$data = array();
$data['error'] = 1;
$flag = 0;

$ConfigObj = new GeneralConfig();
$config = $ConfigObj->find(1);

//$config_res = mysql_query("SELECT `minimum_stay` FROM `jos_resman_general_config` WHERE `id` = 1");
//$config = mysql_fetch_assoc($config_res);

if($diff = dateDiff("/", $_POST['end_date'], $_POST['start_date']) < $config->minimum_stay){
	$data['msg'] = "The minimum stay in a home is ".$config->minimum_stay;
}
else{
	$UnitObj = new Unit();
	$blocked_res = mysql_query("SELECT * FROM `".$UnitObj->get_table_name()."` WHERE `id` = $id");
	$blocked_row = mysql_fetch_assoc($blocked_res);
	$blocked_dates = $blocked_row['blocked_dates'];
	$blocked_dates = explode(",", $blocked_dates);
	for($i = $start_date_str; $i < $end_date_str; $i = add_date($i, 1)){
		if( in_array(parse_dates($i), $blocked_dates ) ){
			$flag = 1;
			break;
		}
	}
	if($flag == 1){
		$data['msg'] = "Dates not available for booking";
	}
	else{
		$flag = 0;
		$BookingObj = new Booking();
		$confirmed_res = mysql_query("SELECT * FROM `".$BookingObj->get_table_name()."` WHERE `uid` = $id AND confirmed = 1");
		while($row = @mysql_fetch_assoc($confirmed_res)){
			$data['other'] = $row;
			if( $start_date >= $row['startdate'] || $end_date <= $row['enddate'] || ( $start_date < $row['startdate'] && $end_date > $row['enddate'] ) ){
				if( ( $row['startdate'] <= $start_date && $row['enddate'] >= $start_date ) || ( $row['startdate'] <= $end_date && $row['enddate'] >= $end_date ) || ( $row['enddate'] <= $end_date && $row['startdate'] >= $start_date ) )
					$flag = 1;
					break;
			}
			//if( ( $start_date < $row['startdate'] || $end_date > $row['enddate'] ) )
		}
		if($flag == 1){
			$data['msg'] = "The selected dates are not available. Please reselect";
		}
		else {
			$data['error'] = 0;
			$data['msg'] = "Dates available";
		}
	}
}
echo json_encode($data);

function parse_dates($date){
	$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	$date = explode("/", $date);
	return $date[1]."/".$months[ ((int)$date[0])-1 ]."/".$date[2];
}
?>